# from cmcc import parse_html
import asyncio
import base64
import hashlib
import json
import random
import sys
import time
import urllib
from datetime import datetime

import aiohttp
import aioredis
import motor
from faker import Faker

from baseHandler import init_logger
from cmcc import query
from util import aes
from util.cmcc_10086 import cmcc_10086_query


def get_ts():
    return str(time.time()).replace('.', '')[:13]


async def noti_task(data, redis):
    await asyncio.sleep(20)
    for n in range(20):
        obj = await db.rechange.find_one({"ordernumber": data})
        try:
            order_id = obj['orderid']
            username = obj['username']
            user_obj = await db.cmcc_username.find_one({"username": username})
            passwd = user_obj['passwd']
            orderdate = obj['orderdate']
            orderstate, message = await cmcc_10086_query(order_id, redis, username, passwd, orderdate, numType="")
            logger.info("%s|%s|%s|%s", obj['ordernumber'], obj.get("payorderno"), orderstate, message)
        except Exception as e:
            logger.error(e, exc_info=True)
            n += 1
            await asyncio.sleep(20)
            continue
        if orderstate == "0":
            await db.rechange.update_one({"ordernumber": data}, {"$set": {"message": message}})
            break
        elif orderstate == "1":
            logger.info("%s|充值失败", data)
            await redis.lpush("cmcc_failed", obj['ordernumber'])
            await db.rechange.update_one({"ordernumber": data}, {"$set": {"message": message}})
            break
        else:
            logger.info('%s|第%s次查询', obj['ordernumber'], n)
            await asyncio.sleep(2*60*60)


async def periodic(proxy_redis):
    orderlist = await aioredis.create_redis(address=('localhost', 6379), loop=loop)
    while True:
        try:
            ordernumber = await orderlist.brpop('cmcc_success', encoding='utf-8')
            logger.info("开始查询充值结果%s", ordernumber)
            loop.create_task(noti_task(ordernumber[1], proxy_redis))
        except Exception as e:
            logger.info(e)
            await asyncio.sleep(1)
            continue
    # else:
    #     orderlist.close()
    #     await orderlist.wait_closed()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()

    logger = init_logger('cmcc', '/app/log/cs_cmcc/recharge%s.log' % sys.argv[1])
    redis = loop.run_until_complete(
            aioredis.create_redis(address=('localhost', 6379), loop=loop)
        )
    task = asyncio.Task(periodic(redis))
    client = motor.motor_tornado.MotorClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
    db = client.cs_recharge
    loop.run_forever()
